package cn.sdhuijin.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.sdhuijin.model.CustomApplySet;
import cn.sdhuijin.model.OfficialLoan;
import cn.sdhuijin.model.User;
import cn.sdhuijin.service.LoanService;
import cn.sdhuijin.service.UserService;
import cn.sdhuijin.utils.CommonUtil;
import cn.sdhuijin.utils.ConstantStr;

@Controller
@RequestMapping(value = { "/loan" })
public class LoanController {

	@Inject
	private LoanService loanService;
	@Inject
	private UserService userService;

	@ResponseBody
	@RequestMapping(value = { "/saveCustomApplyInfo" })
	public Map<String, Object> saveCustomApplyInfo(OfficialLoan loan,
			HttpSession session) {
		session.invalidate();
		
		Map<String, Object> map = new HashMap<String, Object>();
		List<User> managerList = userService.getLoanManagerList(
				loan.getBankId(), ConstantStr.USER_TYPE_MANAGER);
		User manager = null;
		if (managerList != null && managerList.size() > 0) {
			int randomNum = CommonUtil.GenerateRandomNum(0, managerList.size());
			manager = managerList.get(randomNum);
			CommonUtil.sendMsg(manager.getTelphone(), "您有一条新的贷款申请需要处理，贷款申请人为："
					+ loan.getCustomName() + ",手机号码为：" + loan.getTelphone());
			loan.setManagerId(manager.getId());
			loan.setManagerName(manager.getName());
			loan.setManagerTel(manager.getTelphone());
		}
		loan.setApplyDate(CommonUtil.formatDate(new Date()));
		loan.setStatus(ConstantStr.APPLY_STATUS_WAITING);
		loanService.saveCustomApplyInfo(loan);
		map.put("success", true);
		return map;
	}

	@ResponseBody
	@RequestMapping(value = { "/searchCustomApplyInfo" })
	public Map<String, Object> searchCustomApplyInfo(
			@RequestParam("telphone") String telphone, HttpSession session) {
		session.invalidate();

		Map<String, Object> map = new HashMap<String, Object>();
		List<CustomApplySet> customApplySetList = new ArrayList<CustomApplySet>();
		List<OfficialLoan> officialLoanList = loanService
				.searchCustomApplyListByTelphone(telphone);
		if (officialLoanList != null && officialLoanList.size() > 0) {
			for (int i = 0; i < officialLoanList.size(); i++) {
				OfficialLoan OfficialLoan = officialLoanList.get(i);
				CustomApplySet customApplySet = new CustomApplySet();
				customApplySet
						.setEvaluateLevel(OfficialLoan.getEvaluateLevel());
				customApplySet.setApplyDate(OfficialLoan.getApplyDate());
				customApplySet.setApplyId(String.valueOf(OfficialLoan.getId()));
				customApplySet
						.setApplyType(ConstantStr.APPLY_LOAN_TYPE_OFFICIAL);
				customApplySet.setManagerName(OfficialLoan.getManagerName());
				customApplySet.setStatus(OfficialLoan.getStatus());
				customApplySet.setTelphone(OfficialLoan.getManagerTel());
				customApplySetList.add(customApplySet);
			}
		}
		map.put("datas", customApplySetList);
		return map;
	}

	@RequestMapping(value = { "/saveEvaluateInfo" })
	public ModelAndView saveEvaluateInfo(
			@RequestParam("evaluateLevel") String evaluateLevel,
			@RequestParam("evaluateRemarks") String evaluateRemarks,
			@RequestParam("applyId") String applyId,
			@RequestParam("applyType") String applyType) {
		ModelAndView modelAndView = new ModelAndView("redirect:/schedulesearch");
		// 贷款申请类别为公务员贷款
		if (ConstantStr.APPLY_LOAN_TYPE_OFFICIAL.equals(applyType)) {
			OfficialLoan loan = loanService.searchOne(applyId);
			if (CommonUtil.allIsNotEmpty(evaluateLevel)) {
				loan.setEvaluateLevel(evaluateLevel);
			}
			if (CommonUtil.allIsNotEmpty(evaluateRemarks)) {
				loan.setEvaluateRemarks(evaluateRemarks);
			}
			loan.setEvaluateDate(CommonUtil.formatDate(new Date()));
			loanService.saveCustomEvaluateInfo(loan);
		}
		return modelAndView;
	}

	/**
	 * 获取短信验证码
	 * 
	 * @param telephone
	 *            手机号
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = { "getMsgCode" })
	public Map<String, Object> getMsgCode(
			@RequestParam("telphone") String telphone, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		String randomNum = CommonUtil.GenerateSixRandomNum();
		session.setAttribute("searchPhone", telphone);
		session.setAttribute("searchCode", randomNum);
		Boolean flag = CommonUtil.sendMsg(telphone,
				"尊敬的客户，您好！您正在进行枣庄农商行业务办理申请业务，验证码：" + randomNum
						+ ",请输入正确的验证码完成申请。【请勿向任何人提供您收到的短信验证码】");
		if (flag) {
			map.put("message", "发送成功");
		} else {
			map.put("message", "发送失败");
		}
		map.put("success", flag);
		return map;
	}

	/**
	 * 检查手机号和短信验证码是否一致
	 * 
	 * @param telphone
	 *            手机号
	 * @param msgCode
	 *            短信验证码
	 * @param session
	 * @return
	 */
	public boolean checkConfirmCode(String telphone, String msgCode,
			HttpSession session) {
		boolean checkResult = true;
		String sessionPhone = (String) session.getAttribute("searchPhone");
		String sessionCode = (String) session.getAttribute("searchCode");
		if (sessionPhone == null || sessionCode == null
				|| !sessionPhone.equals(telphone)
				|| !sessionCode.equals(msgCode)) {
			checkResult = false;
		}
		return checkResult;
	}

	/**
	 * 检查手机号和短信验证码是否一致
	 * 
	 * @param telphone
	 *            手机号
	 * @param msgCode
	 *            短信验证码
	 * @param session
	 * @return
	 */
	@RequestMapping(value = { "checkConfirmCode" })
	public String checkMsgCode(@RequestParam("telphone") String telphone,
			@RequestParam("msgCode") String msgCode, HttpSession session,
			HttpServletResponse response) {
		boolean checkResult = false;
		String sessionPhone = (String) session.getAttribute("searchPhone");
		String sessionCode = (String) session.getAttribute("searchCode");
		if (sessionPhone != null && sessionCode != null
				&& sessionPhone.equals(telphone) && sessionCode.equals(msgCode)) {
			checkResult = true;
		}
		try {
			response.getWriter().print(checkResult);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
